package com.example.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.junit.platform.commons.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @description:
 * @author: guoc
 * @createDate: 2020/5/8 16:35
 */
public class AbnerRealm extends AuthorizingRealm {


    public final HashMap userInfoMap =new HashMap();
    {
        userInfoMap.put("abner","123");
        userInfoMap.put("candy","123");
    }

    public final HashMap<String,Set<String>> permissionsMap =new HashMap();
    {
        Set<String> set1=new HashSet<>();
        Set<String> set2=new HashSet<>();
        set1.add("video:find");
        set1.add("video:buy");

        set2.add("video:add");
        set2.add("video:del");
        permissionsMap.put("abner",set1);
        permissionsMap.put("candy",set2);
    }

    public final HashMap<String,Set<String>> rolesMap =new HashMap();
    {
        Set<String> set3=new HashSet<>();
        Set<String> set4=new HashSet<>();
        set3.add("role1");
        set3.add("role2");
        set4.add("role3");
        rolesMap.put("abner",set3);
        rolesMap.put("candy",set4);
    }



    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权进入---------->");
        String name = (String) principalCollection.getPrimaryPrincipal();
        //模拟根据name从数据库查询角色和权限
        Set<String> permissions =getPermissionsByname(name);
        Set<String> roles =getRolesByname(name);

        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    private Set<String> getRolesByname(String name) {
        return rolesMap.get(name);
    }

    private Set<String> getPermissionsByname(String name) {

        return permissionsMap.get(name);
    }

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证进入----------->");
        //token获取用户名,用户输入
        String name = (String) authenticationToken.getPrincipal();
        //模拟数据库查询出密码（根据用户名）
        String pwd=userInfoMap.get(name).toString();
        if (StringUtils.isBlank(pwd)){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(name,pwd,getName());

        return simpleAuthenticationInfo;
    }
}
